Page({
  data: {
    taskList: [],
    completedTasks: [],
    showSidebar: false
  },

  onLoad() {
    this.loadTaskList();
    this.loadCompletedTasks();
  },

  onShow() {
    this.loadTaskList();
    this.loadCompletedTasks();
  },

  onUnload() {
    this.clearAllTimers();
  },

  toggleSidebar() {
    this.setData({
      showSidebar: !this.data.showSidebar
    });
  },

  loadTaskList() {
    const allTasks = wx.getStorageSync('taskList') || [];
    const now = new Date();
    // 分离未完成的任务
    const uncompletedTasks = allTasks.filter(task => !task.completed);
    
    // 将任务分为未过期和已过期两组
    const futureTasks = [];
    const pastTasks = [];
    
    uncompletedTasks.forEach(task => {
      const targetDate = new Date(task.targetDate);
      if (targetDate >= now) {
        futureTasks.push(task);
      } else {
        pastTasks.push(task);
      }
    });
    
    // 未过期任务按时间升序排序
    futureTasks.sort((a, b) => new Date(a.targetDate) - new Date(b.targetDate));
    // 已过期任务按时间降序排序
    pastTasks.sort((a, b) => new Date(b.targetDate) - new Date(a.targetDate));
    
    // 合并任务列表：未过期任务在前，已过期任务在后
    const taskList = [...futureTasks, ...pastTasks];
    
    taskList.forEach(task => {
      task.countdown = this.calculateCountdown(task.targetDate);
      task.progress = this.calculateProgress(task.targetDate, task.createTime);
      task.isRunning = false;
      
      if (task.type === 'pregnancy') {
        // 计算当前孕周
        const lastPeriodDate = new Date(task.lastPeriodDate);
        const now = new Date();
        const diffTime = Math.max(0, now - lastPeriodDate);
        const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
        const currentWeek = Math.floor(diffDays / 7) + 1; // 加1是因为怀孕第一天就是第1周第1天

        // 如果已经超过预产期，保持孕周为40周
        const dueDate = new Date(task.dueDate);
        if (now > dueDate) {
          task.week = 40;
        } else {
          task.week = Math.min(40, Math.max(1, currentWeek));
        }
      }
    });

    this.setData({ taskList });
  },

  loadCompletedTasks() {
    const allTasks = wx.getStorageSync('taskList') || [];
    const completedTasks = allTasks.filter(task => task.completed)
      .map(task => ({
        ...task,
        completedTime: new Date(task.completedAt).toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      }))
      .sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt));

    this.setData({ completedTasks });
  },

  calculateCountdown(targetDate) {
    const now = new Date().getTime();
    const target = new Date(targetDate).getTime();
    let diff = Math.max(0, target - now);

    const seconds = Math.floor(diff / 1000) % 60;
    diff = Math.floor(diff / 1000 / 60);
    const minutes = diff % 60;
    diff = Math.floor(diff / 60);
    const hours = diff % 24;
    diff = Math.floor(diff / 24);
    const days = diff % 30;
    diff = Math.floor(diff / 30);
    const months = diff % 12;
    const years = Math.floor(diff / 12);

    return { years, months, days, hours, minutes, seconds };
  },

  calculateProgress(targetDate, createTime) {
    const now = new Date().getTime();
    const target = new Date(targetDate).getTime();
    const start = new Date(createTime).getTime();
    const total = target - start;
    const elapsed = now - start;
    
    if (now >= target) {
      return 100;
    }
    
    if (total <= 0) {
      return 0;
    }
    
    return Math.min(Math.max(Math.floor((elapsed / total) * 100), 0), 100);
  },

  toggleTask(e) {
    const taskId = e.currentTarget.dataset.taskId;
    const taskList = this.data.taskList.map(task => {
      if (task.id === taskId) {
        if (!task.isRunning) {
          this.startTaskTimer(taskId);
        } else {
          this.clearTaskTimer(taskId);
        }
        return { ...task, isRunning: !task.isRunning };
      }
      return task;
    });
    this.setData({ taskList });
  },

  startTaskTimer(taskId) {
    const timer = setInterval(() => {
      const taskList = this.data.taskList.map(task => {
        if (task.id === taskId) {
          const countdown = this.calculateCountdown(task.targetDate);
          const progress = this.calculateProgress(task.targetDate, task.createTime);
          return { ...task, countdown, progress };
        }
        return task;
      });
      this.setData({ taskList });
    }, 1000);
    this[`timer_${taskId}`] = timer;
  },

  clearTaskTimer(taskId) {
    if (this[`timer_${taskId}`]) {
      clearInterval(this[`timer_${taskId}`]);
      this[`timer_${taskId}`] = null;
    }
  },

  clearAllTimers() {
    this.data.taskList.forEach(task => {
      this.clearTaskTimer(task.id);
    });
  },

  resetCountdown(e) {
    const taskId = e.currentTarget.dataset.taskId;
    const taskList = this.data.taskList.map(task => {
      if (task.id === taskId) {
        this.clearTaskTimer(taskId);
        return {
          ...task,
          isRunning: false,
          countdown: this.calculateCountdown(task.targetDate),
          progress: this.calculateProgress(task.targetDate, task.createTime)
        };
      }
      return task;
    });
    this.setData({ taskList });
  },

  markAsCompleted(e) {
    const taskId = e.currentTarget.dataset.taskId;
    const now = new Date();
    const taskList = this.data.taskList.map(task => {
      if (task.id === taskId) {
        return {
          ...task,
          completed: true,
          completedAt: now.toISOString(),
          isRunning: false
        };
      }
      return task;
    });

    this.clearTaskTimer(taskId);
    wx.setStorageSync('taskList', taskList);
    
    // 刷新任务列表和已完成列表
    this.loadTaskList();
    this.loadCompletedTasks();

    // 显示完成提示
    wx.showToast({
      title: '已完成',
      icon: 'success',
      duration: 1500
    });

    // 自动打开侧边栏显示完成的任务
    setTimeout(() => {
      this.setData({ showSidebar: true });
    }, 1500);
  },

  navigateToSetting() {
    wx.navigateTo({
      url: '/pages/setting/setting'
    });
  }
});
